<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row v-show="useShow">
        <a-col :span="8">
          <a-form-item label="领用时间" v-bind="validateInfos.usedDate">
            <a-date-picker v-model:value="formData.usedDate" value-format="YYYY-MM-DD" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="领用人" v-bind="validateInfos.outPerson">
            <a-input v-model:value="formData.outPerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="确认人" v-bind="validateInfos.confirmPerson">
            <a-input v-model:value="formData.confirmPerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-show="returnShow">
        <a-col :span="8">
          <a-form-item label="归还日期" v-bind="validateInfos.returnDate">
            <a-date-picker v-model:value="formData.returnDate" value-format="YYYY-MM-DD" style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="归还人" v-bind="validateInfos.putPerson">
            <a-input v-model:value="formData.putPerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="确认人" v-bind="validateInfos.confirmPerson">
            <a-input v-model:value="formData.confirmPerson" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="用途" v-bind="validateInfos.purpose">
            <a-input
              v-model:value="formData.purpose"
              rows="1"
              :disabled="disabled"
              style="width: 850px; border-radius: 4px 4px 4px 4px; opacity: 1; border: 0.5px solid #dddddd"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-input
              v-model:value="formData.remark"
              rows="1"
              :disabled="disabled"
              style="width: 850px; border-radius: 4px 4px 4px 4px; opacity: 1; border: 0.5px solid #dddddd"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <BasicTable @register="registerTable" :rowSelection="rowSelection" :pagination="false" :dataSource="chemicalList" :disabled="disabled">
      插槽:table标题
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="selectAddChemical">添加标准物质</a-button>
        <template v-if="selectedRowKeys.length > 0">
          <a-dropdown>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="batchHandleDelete">
                  <Icon icon="ant-design:delete-outlined"></Icon>
                  删除
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              <span>批量操作 </span>
              <icon icon="akar-icons:chevron-down" />
            </a-button>
          </a-dropdown>
        </template>
      </template>
      插槽：行内操作按钮
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </a-spin>
  <ChemicalSelectModal rowKey="id" @register="registerSelChemicalModal" @getSelectResult="onSelectChemicalOk" style="height: 40px; overflow: auto" />
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../LabChemicalUsed.api';
  import { Form } from 'ant-design-vue';
  import { ActionItem, BasicTable, TableAction } from '/@/components/Table/index';
  import { useModal } from '/@/components/Modal/index';
  import ChemicalSelectModal from '../components/ChemicalSelectModal.vue';
  // import { ColEx } from '@/components/Form/src/types/index';
  import { useListPage } from '/@/hooks/system/useListPage';

  import { describeColumns } from '../LabChemicalUsedDescribe.data';
  import { deleteOne } from '../LabChemicalUsedDescribe.api';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    usedDate: '',
    outPerson: '',
    putPerson: '',
    purpose: '',
    returnDate: '',
    confirmPerson: '',
    remark: '',
  });
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {};
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });
  const useShow = ref(true);
  const returnShow = ref(false);
  // const adaptiveColProps: Partial<ColEx> = {
  //   xs: 24, // <576px
  //   sm: 24, // ≥576px
  //   md: 24, // ≥768px
  //   lg: 12, // ≥992px
  //   xl: 12, // ≥1200px
  //   xxl: 8, // ≥1600px
  // };
  const [registerSelChemicalModal, selChemicalModal] = useModal();
  const { tableContext, createMessage } = useListPage({
    tableProps: {
      columns: describeColumns,
      canResize: false,
      useSearchForm: false,
      formConfig: {
        // baseColProps: adaptiveColProps,
        labelAlign: 'left',
        labelCol: {
          xs: 24,
          sm: 24,
          md: 24,
          lg: 9,
          xl: 7,
          xxl: 5,
        },
        wrapperCol: {},
      },
      showIndexColumn: true,
    },
  });

  // 注册 ListTable
  const [registerTable, { reload, setProps, setLoading, updateTableDataRecord }, { rowSelection, selectedRowKeys }] = tableContext;

  // 选择添加标准物质
  function selectAddChemical() {
    selChemicalModal.openModal();
  }

  /**
   * 操作栏
   */
  function getTableAction(record): ActionItem[] {
    return [
      {
        label: '删除',
        color: 'error',
        popConfirm: {
          title: '是否确认删除',
          width: 155,
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    chemicalList.value = chemicalList.value.filter((chemical) => chemical.id !== record.id);
  }

  const chemicalList = ref();
  async function onSelectChemicalOk(selectRows) {
    chemicalList.value = selectRows.value; //后端查出的标物信息
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    chemicalList.value = chemicalList.value.filter((chemical) => !selectedRowKeys.value.includes(chemical.id));
  }

  /**
   * 新增
   */
  function add(show) {
    if (show === 'return') {
      useShow.value = false;
      returnShow.value = true;
    }
    chemicalList.value = [];
    // edit({});
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, {});
    });
  }

  /**
   * 编辑
   */
  async function edit(record) {
    chemicalList.value = await defHttp.get({ url: '/chemical/labChemicalUsedDescribe/queryList?usedId=' + record.id });
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */

  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    for (let i = 0; i < chemicalList.value.length; i++) {
      chemicalList.value[i].chemicalId = chemicalList.value[i].id;
      chemicalList.value[i].id = '';
    }
    const target = JSON.parse(JSON.stringify(chemicalList.value));

    model.listDescribe = target;
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 250px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
